package com.yzy.signature1

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.util.DisplayMetrics
import android.view.View
import com.blankj.utilcode.util.*
import com.picc.cn.pdfui.*
import com.sunyard.base.base.BaseActivity
import com.sunyard.base.viewModel.BaseViewModel
import kotlinx.android.synthetic.main.activity_signature.*
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.*

class SignatureActivity : BaseActivity<BaseViewModel>() {
    val filePath=PathUtils.getExternalAppPicturesPath()+"/signature_v1.png"
    override fun initLayout()=R.layout.activity_signature

    override fun initViewModel()=BaseViewModel::class.java

    override fun initLiveData() {

    }
    private var core: MuPDFCore? = null
    private var mFileName: String? = null
    private var mDocView: ReaderView? = null
    private var mSearchTask: SearchTask? = null
    var density = 0f//屏幕分辨率密度
    var in_path=""
    var out_path=PathUtils.getExternalStoragePath()+"/savePDF.pdf"
    var editMode=false
    override fun initView() {
        //计算分辨率密度

        //计算分辨率密度
        val metric = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metric)
        density = metric.density

        initPDFViewer()
        createUI()
        mBtnClear.setOnClickListener {
            mSignatureView.clear()
        }
        mBtnSave.setOnClickListener {
            if(FileUtils.isFileExists(out_path)){
                FileUtils.delete(out_path)
            }
            try {
                mSignatureView.save(filePath,true,0)
                ToastUtils.showLong("保存成功 可复用签名图片在 $filePath")
            }catch (e:Exception){
                e.printStackTrace()
            }
            val scale: Float = mDocView!!.mScale ///得到放大因子

            val savePdf = SavePdf(in_path, out_path)
            savePdf.setScale(scale)
            savePdf.setPageNum(mDocView!!.getDisplayedViewIndex() + 1)

            savePdf.setWidthScale(
                1.0f * mDocView!!.scrollX / mDocView!!.getDisplayedView().getWidth()
            ) //计算宽偏移的百分比

            savePdf.setHeightScale(
                1.0f * mDocView!!.scrollY / mDocView!!.getDisplayedView().getHeight()
            ) //计算长偏移的百分比


            savePdf.setDensity(density)
            /** 此处可以做处理，将之前保存的可复用的签名图片读取出来，赋予bitmap变量,以达到复用*/
            val bitmap = Bitmap.createBitmap(
                mSignatureView.width, mSignatureView.height,
                Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(bitmap)
            mSignatureView.draw(canvas)
            savePdf.setBitmap(bitmap)
            savePDF(savePdf)
        }
        mBtnOpenList.setOnClickListener {
            ActivityUtils.startActivity(PDFListActivity::class.java)
        }

        mBtnEdit.setOnClickListener {
            if(editMode){
                mBtnEdit.text="编辑"
                mSignatureView.clear()
                mSignatureView.visibility= View.GONE
            }else{
                mBtnEdit.text="取消编辑"
                mSignatureView.clear()
                mSignatureView.visibility= View.VISIBLE
            }
            editMode=!editMode
        }
    }
    fun savePDF(savePdf: SavePdf){
        try {
            savePdf.addText()
            LogUtils.d("TEST 保存的PDF $out_path")

            core = MuPDFCore(out_path)
            mDocView!!.adapter = PageAdapter(ActivityUtils.getTopActivity(), core)
//            val temp = in_path
//            in_path = out_path
//            out_path = temp
            mDocView!!.mScale=1.0f
            mDocView!!.displayedViewIndex = mDocView!!.displayedViewIndex
            mSignatureView.clear()
            mSignatureView.visibility=View.GONE
            ToastUtils.showShort("保存成功")
        } catch (e: Exception) {
            e.printStackTrace()
            ToastUtils.showShort("保存失败")
        }
//        ThreadUtils.executeByIo(object :ThreadUtils.Task<Boolean>(){
//            override fun doInBackground(): Boolean {
//                try {
//                    savePdf.addText()
//                    LogUtils.d("TEST 保存的PDF $out_path")
//                    core = MuPDFCore(out_path)
//                    mDocView!!.adapter = PageAdapter(ActivityUtils.getTopActivity(), core)
//                    val temp = in_path
//                    in_path = out_path
//                    out_path = temp
//                    mDocView!!.mScale=1.0f
//                    mDocView!!.displayedViewIndex = mDocView!!.displayedViewIndex
//                    return true
//                } catch (e: Exception) {
//                    e.printStackTrace()
//                    return false
//                }
//
//            }
//
//            override fun onSuccess(result: Boolean?) {
//                if(result!=null&&result) {
//                    ToastUtils.showShort("保存成功")
//                }else{
//                    ToastUtils.showShort("保存失败")
//                }
//            }
//
//            override fun onFail(t: Throwable?) {
//                ToastUtils.showShort("保存失败")
//                t!!.printStackTrace()
//            }
//
//            override fun onCancel() {
//            }
//        })
    }
    fun initPDFViewer(){
        if (core == null) {
            val intent = intent
            var buffer: ByteArray? = null
            if (Intent.ACTION_VIEW == intent.action) {
                val uri = intent.data
                println("URI to open is: $uri")
                if (uri!!.scheme == "file") {
                    in_path = uri.path!!
                    core = openFile(in_path)
                } else {
                    try {
                        val `is` = contentResolver.openInputStream(uri)
                        var len: Int
                        val bufferStream =
                            ByteArrayOutputStream()
                        val data = ByteArray(16384)
                        while (`is`!!.read(data, 0, data.size).also { len = it } != -1) {
                            bufferStream.write(data, 0, len)
                        }
                        bufferStream.flush()
                        buffer = bufferStream.toByteArray()
                        `is`.close()
                    } catch (e: IOException) {
                        val reason = e.toString()
                        val res = resources
                        val alert: AlertDialog = AlertDialog.Builder(this).create()
                        title = String.format(
                            Locale.ROOT,
                            res.getString(R.string.cannot_open_document_Reason),
                            reason
                        )
                        alert.setButton(
                            AlertDialog.BUTTON_POSITIVE,
                            getString(R.string.dismiss)
                        ) { dialog, which -> finish() }
                        alert.show()
                        return
                    }
                    core = openBuffer(buffer, intent.type!!)
                }
                SearchTaskResult.set(null)
            }

            if (core != null && core?.countPages() == 0) {
                core = null
            }
        }
    }
    private fun openFile(path: String): MuPDFCore? {
        val lastSlashPos = path.lastIndexOf('/')
        mFileName = if (lastSlashPos == -1) path else path.substring(lastSlashPos + 1)
        println("Trying to open $path")
        core = try {
            MuPDFCore(path)
        } catch (e: java.lang.Exception) {
            println(e)
            return null
        } catch (e: OutOfMemoryError) {
            //  out of memory is not an Exception, so we catch it separately.
            println(e)
            return null
        }
        return core
    }

    private fun openBuffer(buffer: ByteArray, magic: String): MuPDFCore? {
        println("Trying to open byte buffer")
        core = try {
            MuPDFCore(buffer, magic)
        } catch (e: java.lang.Exception) {
            println(e)
            return null
        }
        return core
    }

    fun createUI() {
        if (core == null) return
        mDocView = object : ReaderView(this) {
            override fun onMoveToChild(i: Int) {
                if (core == null) return
                super.onMoveToChild(i)
            }

            override fun onTapMainDocArea() {

            }

            override fun onDocMotion() {

            }
        }
        mDocView?.adapter = PageAdapter(this, core)
        mSearchTask = object : SearchTask(this, core) {
            override fun onTextFound(result: SearchTaskResult) {
                SearchTaskResult.set(result)
                // Ask the ReaderView to move to the resulting page
                mDocView?.displayedViewIndex = result.pageNumber
                // Make the ReaderView act on the change to SearchTaskResult
                // via overridden onChildSetup method.
                mDocView?.resetupChildren()
            }
        }
        // Reenstate last state if it was recorded
        val prefs =
            getPreferences(Context.MODE_PRIVATE)
        mDocView?.displayedViewIndex = prefs.getInt("page$mFileName", 0)
        rootView.addView(mDocView,0)
    }





}